<?php

namespace app\jigou\controller\qingdongams\customer;

use addons\qingdongams\model\Flow;
use addons\qingdongams\model\FormField;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Staff;
use app\jigou\controller\qingdongams\Base;
use app\common\library\Auth;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\Contract;
use addons\qingdongams\model\ReceivablesOther;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use addons\qingdongams\model\ReceivablesPlan;
use think\Db;
use think\Exception;
use think\Session;

/**
 * 回款管理
 * @desc 操作文档：https://doc.fastadmin.net/qingdongams
 * @desc 软件介绍：https://www.fastadmin.net/store/qingdongams.html
 * @desc 售后微信：qingdong_crm
 */
class Receivables extends Base {
	protected $relationSearch = true;
	protected $searchFields   = 'id';
	/**
	 * @var \addons\qingdongams\model\Receivables
	 */
	protected $model = null;


	public function _initialize() {
		parent::_initialize();
		$this->model = new \addons\qingdongams\model\Receivables;
	}


	/**
	 * 查看
	 */
	public function index() {
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {

            //0:全部 1：我负责的 2：下属负责的
            $type = input('type',0);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            switch($type){
                case 1:
                    $staff = Staff::info();
                    $wheres['receivables.owner_staff_id'] =  $staff->id;
                    break;
                case 2:
                    $wheres['receivables.owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                    break;
                default:
                    $wheres['receivables.owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                    break;

            }
            $ids=[];
            $group_id=input('group_id');
            $staff_id=input('staff_id');
            if ($group_id) {//角色组
                $ids = Staff::getGroupStaffIds($group_id);
            }
            if ($staff_id) {
                $ids = $staff_id;
            }
            if ($group_id || $staff_id) {
                $wheres['receivables.owner_staff_id'] = ['in', $ids];
            }
			$list = $this->model->alias("receivables")->where($where)
                ->where($wheres)->with(['customer', 'contract','ownerStaff'])->join("qingdongams_customer customer", "receivables.customer_id=customer.id", "left")->where(array("customer.customer_type" =>"家长"))->where("customer.jigou_id", Session::get("jigou_id"))->field("receivables.*")->order($sort, $order)->paginate($limit);

			$result = array("total" => $list->total(), "rows" => $list->items());

			return json($result);
		}

        $field = FormField::getFields(FormField::RECEIVABLES_TYPE);
        $this->assignconfig('fields', $field);
		return $this->view->fetch();
	}


	/**
	 * 添加
	 */
	public function add($ids=null) {
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$params = $this->preExcludeFields($params);
                // 表单验证
                if (($result = $this->qingdongamsValidate($params, 'Receivables', 'create')) !== true) {
                    $this->error($result);
                }
                $result = FormField::checkFields(FormField::RECEIVABLES_TYPE, $params);
                if ($result !== true) {
                    $this->error($result);
                }

                if ($this->model->where(['number' => $params['number'], 'contract_id' => $params['contract_id']])->find()) {
                    $this->error('回款编号已存在');
                }
                $contract=Contract::where(['id'=>$params['contract_id']])->find();
                if(empty($contract)){
                    $this->error('订单不存在');
                }
                if($contract['check_status'] != 2){
                    $this->error('当前订单未审核通过');
                }
				$result = false;

                $params = Form::updateFormParams('examine', $params);

				Db::startTrans();
				try {
                    $params = Form::updateFormParams('examine', $params);

                    $params['owner_staff_id'] = $contract['owner_staff_id'];
                    $result=$this->model::createReceivables($params);
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were inserted'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
        $staff=Staff::where([])->column('name','id');
        $this->assign('staff', $staff);

        $flow= Flow::getsteplist(Flow::RECEIVABLES_STATUS);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $customer_id = input('customer_id');
        $contract_id = input('contract_id');
        $this->assign('contract_id', $contract_id);
        $this->assign('customer_id', $customer_id);
        $this->assign('customer', Customer::get($customer_id));
        $this->assign('contract', Contract::get($contract_id));
        $this->assign('flow',$flow);
        $this->view->assign('ids',$ids);
        $this->view->assign('form_data', Form::getDataValue('examine'));
        $this->assign('createNum', get_num('receivables'));
		return $this->view->fetch();
	}

    /**
     * 回款详情
     */
	public function detail($ids = null) {
		$row = $this->model->where(['id' => $ids])->with(['customer', 'contract','plan','ownerStaff'])->find();

		$status = [0 => '待审核', 1 => '审核中', 2 => '审核通过', 3 => '审核未通过', 4 => '撤销', 5 => '未提交'];


		$this->assign('status', $status);
        $row   = $row->toArray();
        $row = ReceivablesOther::getOther($row);

//标记通知已读
        Message::setRead(Message::RECEIVABLES_TYPE, $ids, $this->_staff->id);
        $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::RECEIVABLES_TYPE,$ids));

        $this->assign('flow',Flow::getstepdetail(Flow::RECEIVABLES_STATUS, $ids));
		$this->assign('row', $row);
        $this->assign('form_data', Form::getDataValue('examine',$row));
		$this->assign('ids', $ids);
        $this->assignconfig("idinfo", ['id' => $ids]);
		return $this->view->fetch();
	}

	/**
	 * 删除
	 */
	public function del($ids = "") {
		if (!$this->request->isPost()) {
			$this->error(__("Invalid parameters"));
		}
		$ids                 = $ids ? $ids : $this->request->post("ids");
		$row                 = $this->model->get($ids);
		$this->modelValidate = true;
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		Auth::instance()->delete($row['id']);
		$this->success();
	}

    /**
     * 获取客户列表
     */
    public function getcustomer()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $staff = Staff::info();
        $staff_id = $staff->id;
        $whereStaff = function ($query) use ($staff_id) {
            $query->where(['ro_staff_id' => ['like', "%,{$staff_id},%"]])
                ->whereOr('rw_staff_id', 'like', "%,{$staff_id},%")
                ->whereOr(['owner_staff_id' => ['in', Staff::getMyStaffIds()]]);
        };
        $customer = Customer::where($whereStaff)->where($where)->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $customer->items(), 'total' => $customer->total()]);
    }

    /**
     * 获取订单列表
     */
    public function getcontract()
    {
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $customer_id = input('customer_id', 0);
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $where['check_status'] = 2;
        $where['customer_id'] = $customer_id;
        $contacts = Contract::where($where)->field('id,name,num')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        $data = [];
        $item=$contacts->items();
        foreach ($item as $v) {
            $v->name=$v['num'] . "（{$v['name']}）";
        }
        return json(['list' => $item, 'total' =>$contacts->total()]);
    }

    /**
     * 获取审批人列表
     */
    public function getstaff(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }



    /**
     * 导入回款信息
     * @return string|void
     */
    public function import()
    {
        set_time_limit(0);
        if ($this->request->isPost()) {

            $file = $this->request->request('file');
            if (!$file) {
                $this->error(__('Parameter %s can not be empty', 'file'));
            }
            $filePath = ROOT_PATH . 'public' . $file;
            if (!is_file($filePath)) {
                $this->error(__('No results were found'));
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error(__('Unknown data format'));
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);

                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表

            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行

            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            //开始读取数据
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[$currentRow][] = $val;
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
            }
            if (!isset($fields[1])) {
                $this->error('导入文件第一行没有数据');
            }
            $lastid = $this->model->order('id desc')->value('id');

            $lastid = $lastid + 5;//防止重复

            $contractRow = [];
            $errorInfo = [];

            $fieldnames = FormField::where(['types' => FormField::RECEIVABLES_TYPE])->column('field', 'name');
            $customerNames=Customer::where([])->column('id,owner_staff_id','name');
            $contractNames=Contract::where([])->column('id,name,num','num');

            $fn = [];
            $nums=$this->model->where([])->column('number');
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                foreach ($values as $l) {

                    $fn[] = $fieldnames[$l] ?? '';
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    if ($val instanceof RichText) {//富文本转换字符串
                        $val = $val->__toString();
                    }
                    $values[] = is_null($val) ? NULL : trim($val);
                }
                $lastid++;
                $addReceivables = ['id' => $lastid];
                $customer=isset($customerNames[$values[0]])?$customerNames[$values[0]]:0;
                if(empty($customer)){
                    $errorInfo[] = "第{$currentRow}行，客户名称不存在;";
                    continue;
                }
                $contract=isset($contractNames[$values[1]])?$contractNames[$values[1]]:0;
                if(empty($contract)){
                    $errorInfo[] = "第{$currentRow}行，订单编号不存在;";
                    continue;
                }
                $addReceivables['contract_id']=$contract['id'];
                $addReceivables['customer_id']=$customer['id'];
                $addReceivables['owner_staff_id']=$customer['owner_staff_id'];
                $addReceivables['create_staff_id']=$customer['owner_staff_id'];

                foreach ($values as $kv => $value) {
                    if (!isset($fn[$kv]) || empty($fn[$kv])) {
                        continue;
                    }
                    $addReceivables[$fn[$kv]] = $value;
                }
                if (empty($addReceivables['number'])) {
                    $errorInfo[] = "第{$currentRow}行，回款编号不能为空;";
                    continue;
                }
                if (in_array($addReceivables['number'], $nums)) {
                    $errorInfo[] = "第{$currentRow}行，回款编号`{$addReceivables['number']}`已存在;";
                    continue;
                }
                $contractRow[] = $addReceivables;
            }
            if (!empty($errorInfo)) {
                $this->error(implode(',', $errorInfo));
            }
            Db::startTrans();
            try {
                $this->model::importReceivables($contractRow);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('导入成功');
        }

        return $this->view->fetch();
    }

    /**
     * 模板
     */
    public function template()
    {
        $title = [
            '客户名称',
            '订单编号',

        ];
        $contractData = Form::getDataValue(Form::RECEIVABLES_TYPE);

        foreach ($contractData as $val) {
            $title[] = $val['config']['label'];
        }

        $file = export_excel($title, [], '回款');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $file['fileName']);
        header('Cache-Control: max-age=0');

        $obj = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('导出文件'); //设置标题
        $obj->setActiveSheetIndex(0);
        $obj->getActiveSheet()->setTitle('导出文件');
        /* 循环读取每个单元格的数据 */
        $a = 'A';
        $currentSheet = $obj->getActiveSheet();
        foreach ($title as $key => $value) {
            //读取工作表1
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($a . '1')->getFont()->setBold(true);
            //这里是设置单元格的内容
            $currentSheet->getCell($a . '1')->setValue($value);
            $a++;
        }

        $PHPWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($obj);

        $PHPWriter->save('php://output');
    }

    /**
     * 导出信息
     */
    public function export()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $ids = input('ids');
        $isall = input('isall',0);
        $wheres = array();
        //导出其中几条
        if (isset($ids)) {
            $wheres['id'] = array('in', $ids);
        }
        //导出全部
        if ($isall == 3) {
            unset($wheres['id']);
        }
        //0:全部 1：我负责的 2：下属负责的
        $type = input('type',0);
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        switch($type){
            case 1:
                $staff = Staff::info();
                $wheres['owner_staff_id'] =  $staff->id;
                break;
            case 2:
                $wheres['owner_staff_id'] =  array('in',Staff::getLowerStaffId());
                break;
            default:
                $wheres['owner_staff_id'] =  array('in',Staff::getMyStaffIds());
                break;

        }

        $list = $this->model->with(['customer', 'contract','ownerStaff','receivablesOther'])->where($where)->where($wheres)->order($sort, $order)->select();
        $list = collection($list)->toArray();

        if (!$list) {
            $this->error('无导出数据');
        }
        $title = [
            '序号',
            '客户名称',
            '订单名称',
            '订单编号',

            '负责人',
            '创建时间',
        ];

        $dataValue = Form::getDataValue(Form::RECEIVABLES_TYPE);

        foreach ($dataValue as $val) {
            $title[] = $val['config']['label'];
        }
        foreach ($list as $k => $v) {
            if($v['receivables_other']){//其他客户
                $other=$v['receivables_other']['otherdata'];
                $other=json_decode($other,true);
                $v = array_merge($v, $other);
            }
            $field = array(
                $v['id'],
                $v['customer']['name'] ?? '',
                $v['contract']['name'] ?? '',
                $v['contract']['num'] ?? '',
                $v['owner_staff']['name'] ?? '',
                $v['createtime'],
            );
            foreach ($dataValue as $val) {
                if ($val['component'] == 'uploadImage' || $val['component'] == 'uploadFile') {
                    $field[] = $v[$val['id'] . '_str'] ?? '';
                } else {
                    $field[] = ($v[$val['id']] ?? '');
                }
            }
            $data[] = $field;
        }
        $file = export_excel($title, $data, '回款');
        if ($file['filePath']) {
            $this->success('导出成功', '', $file);
        }
        $this->error('导出失败');
    }

    /*
     * 回款计划列表
     */
    public function plan(){
        $customer_id = input('customer_id');
        $contract_id = input('contract_id');
        $list= [];
        if($customer_id && $contract_id){
            $where['customer_id'] = $customer_id;
            $where['contract_id'] = $contract_id;
            $where['status'] = 0;
            $list = ReceivablesPlan::where($where)->select();
        }
        $this->success('请求成功','',$list);
    }
}
